package appserver;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import session.Session;
import session.SessionID;

public class SessionCleaner extends Thread {
	private ConcurrentHashMap<SessionID,Session> sessionMap;
	private static final boolean DEBUG = true;
	
	public SessionCleaner(ConcurrentHashMap<SessionID,Session> map) {
		this.sessionMap = map;
	}

	@Override
	public void run() {
		this.setPriority(MIN_PRIORITY);
		while(true) {
			Set<SessionID> keys = sessionMap.keySet();
			Iterator<SessionID> it = keys.iterator();
			while (it.hasNext()) {
				SessionID sessId = it.next();
				Session session = sessionMap.get(sessId);
				synchronized (session) {
					if (session.isExpired()) {
						sessionMap.remove(sessId);
						if (DEBUG) System.out.println("Removed expired session: " + sessId.toString());
					}
				}
			}
			try {
				Thread.sleep(20 * 60 * 1000); //20 min frequency
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
